import json
import os
import random
import time

from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.utils.encoding import force_text
from django.utils.functional import Promise
from django.views.decorators.csrf import csrf_exempt
import markdown
from cms.models import Article
from cms.models import Category
import requests


class LazyEncoder(DjangoJSONEncoder):
    """
        解决json __proxy__ 问题
    """

    def default(self, obj):
        if isinstance(obj, Promise):
            return force_text(obj)
        return super(LazyEncoder, self).default(obj)


@csrf_exempt
def post(request):
    post = request.POST

    # 必须字段
    fields = ('title', 'content', 'summary')
    # 可选字段
    # ('cover', 'published','type')
    # type 取值0=html，1=markdown

    for field in fields:
        if not field in post or post.get(field) == '':
            return HttpResponse(json.dumps({
                'status': 0,
                'msg': "'{}'字段必填".format(field)
            }, cls=LazyEncoder), content_type="application/json")

    # 入库
    try:
        type = 0
        if post.get('type'):
            type = int(post.get('type'))

        content = post.get('content')
        if type == 1:
            content = markdown.markdown(content)
        published = False

        if post.get('published') and post.get('published') != '':
            published = str(post.get('published')).capitalize() == 'True'

        # 如果有封面的时候 下载封面，将封面放到本地
        cover = post.get('cover')

        if cover.find('http') == 0:
            r = requests.get(cover, timeout=(3, 7))
            if r.status_code == 200:
                suffix = os.path.splitext(cover)[1]
                # 按照时间命名文件
                filename = '{}{}{}'.format(int(time.time() * 1000000), random.randint(10, 99), suffix)
                BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
                filepath = os.path.join(BASE_DIR, 'static/upload', filename)

                with open(filepath, "wb") as f:  # 开始写文件，wb代表写二进制文件
                    f.write(r.content)
                cover = '/static/upload/{}'.format(filename)

        db = Article(
            title=post.get('title'),
            content=content,
            summary=post.get('summary'),
            cover=cover,
            published=published
        )
        db.save()

        result = {
            'status': 1,
            'msg': 'ok'
        }
    except Exception as e:
        result = {
            'status': 0,
            'msg': str(e)
        }

    return HttpResponse(json.dumps(result, cls=LazyEncoder), content_type="application/json")
